from apps.common.base.views import *
from apps.interface.client.models import Client
from .service import *
import threading
from . import reports
from . import reports_qlw
from apps.system.lessee.dao import LesseeDao
import django.utils.timezone as timezone

class ValidateCodeViewSet(BaseViewSet):
    def get_queryset(self):
        params = getRequestParams(self.request)
    serializer_class = ValidateCodeSerializer

    '''发送验证码'''
    @action(methods=['post'], detail=False, url_path='sendSms',authentication_classes=[],permission_classes=[])
    def sendSmsAPI(self, request):
        params = getRequestParams(request)
        if not params.get("phone"):
            return Response(response_message("手机号不能为空"))
        if len(params.get("phone"))!=11:
            return Response(response_message("手机号格式错误"))
        params['phone'] = params.get("phone")
        params['code'] = random_num(6)
        # 创建一条验证码记录
        # 获取当前时间
        now = timezone.now()
        # 计算当前分钟的开始时间
        start_of_minute = now.replace(second=0, microsecond=0)
        # 计算当前分钟的结束时间
        end_of_minute = start_of_minute + datetime.timedelta(minutes=1)
        # 计算当前小时的开始时间
        start_of_hour = now.replace(minute=0, second=0, microsecond=0)
        # 计算当前小时的结束时间
        end_of_hour = start_of_hour + datetime.timedelta(hours=1)
        
        minute_count = ValidateCode.objects.all().filter(phone=params.get('phone'), createTime__gte=start_of_minute, createTime__lt=end_of_minute).count()
        if minute_count >= 3:
            return Response(response_message("每分钟只能发送3次"))
        hour_count = ValidateCode.objects.filter(phone=params.get('phone'), createTime__gte=start_of_hour, createTime__lt=end_of_hour).count()
        if hour_count >= 10:
            return Response(response_message("每小时只能发送10次"))
        _validateCode = ValidateCode.objects.create(phone=params.get('phone'), code=params.get('code'))
        # 5分钟后状态改为失效
        t = threading.Timer(300, setValidateCodeStatus,(_validateCode,))
        t.start()
        _lessee = LesseeDao().getLessee()
        if isEmptyStr(_lessee.validateCodeCHN):
            return Response(response_message('验证码渠道字段缺失'))
        params['validateCodeCHN'] = _lessee.validateCodeCHN
        sendSmsForAli(params)
        return Response(response_success('发送成功'))

def setValidateCodeStatus(validateCode):
    _validateCode = ValidateCode.objects.get(id=validateCode.id)
    print('更新验证码为失效状态', _validateCode.status)
    if _validateCode.status != 2:
        _validateCode.__dict__.update(**{'status':3})
        _validateCode.save()